import 'dart:convert';

import 'package:intl/intl.dart';
import 'package:xuance/bean/AiWarningitemBean.dart';
import 'package:xuance/bean/PublicKeyBean.dart';
import 'package:xuance/bean/StatisticBean.dart';
import 'package:xuance/bean/TrafficDetailDataBean.dart';
import 'package:xuance/bean/exp.dart';
import 'package:xuance/network/network_service.dart';
import 'package:xuance/util/cache_util.dart';

class CommonApi {
  static Future<PublicKeyBean?> getPubKeyCached() async {
    PublicKeyBean? pubKey = await CacheUtil.getPubKey();
    if (pubKey != null) {
      return pubKey;
    }
    var res = await NetworkService.post(
        url: "sysUser/publicKey", map: {}, isShowLoading: false);
    PublicKeyBean? pubKey1 = res.getTypedData((m) => PublicKeyBean.fromJson(m));
    await CacheUtil.setPubKey(pubKey1);
    return pubKey1;
  }

  static Future<List<StatisticBean>> getStatistic(
      {required String startDate,
      required String endDate,
      required String queryCondition}) async {
    var res = await NetworkService.post(
        url: "dataStatistics/dataStatisticsList",
        map: {
          "startDate": startDate,
          "endDate": endDate,
          "queryCondition": queryCondition
        },
        isShowLoading: false);
    if (res.data is String) {
      var l = jsonDecode(res.data);
      if (l is List) {
        return l.map((m) => StatisticBean.fromJson(m)).toList();
      } else {
        print("不是列表");
        return [];
      }
    } else {
      return res.getTypedList((m) => StatisticBean.fromJson(m)) ?? [];
    }
  }

  static String? formatDate(String timeString) {
    List<String> formats = [
      'yyyy-MM-dd HH:mm:ss', // 格式: 2024-12-26 17:57:26
      'MM/dd/yyyy HH:mm:ss', // 格式: 12/26/2024 17:57:26
      'dd-MM-yyyy HH:mm:ss', // 格式: 26-12-2024 17:57:26
      'yyyy/MM/dd HH:mm', // 格式: 2024/12/26 17:57
      'yyyy年MM月dd日 HH:mm', // 格式: 2024年12月26日 17:57
      'yyyy-MM-dd HH:mm:ss.SSS', // 格式: 2024-12-26 17:57:26.148
      'MM/dd/yyyy HH:mm:ss.SSS', // 格式: 12/26/2024 17:57:26.148
      'dd-MM-yyyy HH:mm:ss.SSS', // 格式: 26-12-2024 17:57:26.148
    ];

    // 尝试不同的格式解析
    for (var format in formats) {
      try {
        DateTime dateTime = DateFormat(format).parse(timeString);
        // 将解析后的时间统一格式化为 yyyy-MM-dd HH:mm:ss（不包含毫秒）
        return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
      } catch (e) {
        continue; // 如果当前格式解析失败，继续尝试下一个格式
      }
    }
    return null; // 如果无法匹配任何格式，返回 null
  }

  static Future<TrafficDetailDataBean?> getTrafficDetail(
      AiWarningItemList bean) async {
    // var map = {
    //   "sip": bean.sip,
    //   "spt": bean.spt,
    //   "dip": bean.dip,
    //   "dpt": bean.dpt,
    //   "protocols": bean.protocols,
    //   "start_time": bean.startDate
    // };
    Map<String, dynamic> map = {};
    // map['sip'] = '10.28.7.16';
    // map['dip'] = '10.28.9.140';
    // map['spt'] = '7612';
    // map['dpt'] = '7004';
    // map['protocols'] = ['tcp'];
    // map['start_time'] = '2024/12/24 10:11:52';
    map['sip'] = bean.sip;
    map['dip'] = bean.dpt;
    map['spt'] = bean.spt;
    map['dpt'] = bean.dpt;
    map['protocols'] = bean.protocols;
    map['start_time'] = formatDate(bean.startDate);

    var res = await NetworkService.post(
        url: "dataStatistics/trafficDetail",
        map: map,
        isShowLoading: false,
        showErrToast: false);
    if (res.data is String) {
      var data = jsonDecode(res.data)['data'];
      if (data != null) {
        return TrafficDetailDataBean.fromJson(data);
      } else {
        throw ApiException(
            code: jsonDecode(res.data)['code'],
            message: jsonDecode(res.data)['message']);
      }
    }
    return res.getTypedData((m) => TrafficDetailDataBean.fromJson(m));
  }
}
